<?php
include_once (S_ROOT . './push/Channel.class.php');
class Push
{
    private $apiurl;
    private $apis;
    private $action;//$req['op']跳转的函数
    private $apiKey 	= 'qAneZ14WaxH1LsRvLadleD4K' ;//安卓
    private $secretKey  = 'Y90K5P39bKcnRqwt7o6P45ioU7ELMboL';
    private $apiKey1    = '55eRZyxQ1uNpMbt9ydU1SxZS';//ios普通版
    private $secretKey1 = 'Yr9GB28CEf54m05z1369Yp9nT5A3WmH2';
    private $apiKey2    = '4hUytGll8QERZiaVK60t8bNZ';//ios专业版
    private $secretKey2 = 'IGObxU13vxScOza6WR3ORfzfIZ1ZVWtU';  
    private $channel;
    private $channel1;
    private $channel2;
    private $version    = 'channel';
    private $user_id	= '651052345775898376';//uid:7202207
    private $channel_id = '3758836349334133197';
    private $optional   =    array();
	private $duibaBaseUrl = 'pinksns://channel/biz/duiba/redirect?redirect=1&url=';
    
    public function __construct($apiurl) {
     	 
        $this->apiurl   	   =    $apiurl;
        $this->channel         =    new Channel($this->apiKey, $this->secretKey);
        $this->channel1        =    new Channel($this->apiKey1, $this->secretKey1);
        $this->channel2        =    new Channel($this->apiKey2, $this->secretKey2);
        $this->apis     = array(
           'queryBindList','deleteTag','pushActivity'
        );
    }
    
    private function init($req){
    	if ($req['user_id']){
    		$this->user_id    =    strval($req['user_id']);
    	}
    	if ($req['channel_id']){
    		$this->channel_id =    strval($req['channel_id']);
    	}
    	if ($req['version']){
    		$this->version    = strval($req['version']);
    	}
    	$this->optional[ Channel::CHANNEL_ID ] = (float)$this->channel_id;
    	$this->optional [ Channel::USER_ID ]   = $this->user_id;
    }
    
    public function execute ($action) {
        if (!in_array($action, $this->apis) || empty($action)){
        	return false;
        }
      
        $req = request();
        $this->init($req);
        $this->action = $action;
        $result = $this->$action($req);
        return $result;
    }
    
    private function pushActivity($req){
    	header("Content-type: application/json");
    	$message_key =    $this->create_guid();
    	$optional    =    array();
    	$device_type =    array('android' => 3,'ios' => 4);//3：android 4：iOS
    	$message_type=    array('android' => 0,'ios' => 1);
    	$status      =    2; //1（开发状态）和 2（生产状态）仅iOS推送使用。
    	$push_type   =    2; //1:单人，2：一群人tag， 3：所有人
    	$data = $this->filterArgumentsOfPassed($req);
		file_put_contents("/tmp/pushActivityReq.txt",date("Y-m-d H:i:s").":".strval(json_encode($req)."\r\n"),FILE_APPEND);
		file_put_contents("/tmp/pushActivityData.txt",date("Y-m-d H:i:s").":".strval(json_encode($data)."\r\n"),FILE_APPEND);
    	if(!$data || empty($req['tag_name'])){
			echo 0;
			exit;
    	}
    	//common
    	$optional[Channel::TAG_NAME]     =  $req['tag_name'];
    	$optional[Channel::DEPLOY_STATUS]=  $status;
    	$data_extra         =    my_json_encode($data['extras']);
    	$len                =    strlen($data_extra);
    	$limit              =    200-$len; 
    	
    	//android
    	$ret  = $this->pushAndroid($optional, $device_type, $message_type, $data, $limit, $push_type, $message_key);

		file_put_contents("/tmp/pushActivityAndroid.txt",date("Y-m-d H:i:s").":".strval(json_encode($ret)."\r\n"),FILE_APPEND);
    	// ios
    	$ret1= $this->pushIos($optional, $device_type, $message_type, $data, $limit, $push_type, $message_key);
		file_put_contents("/tmp/pushActivityios.txt",date("Y-m-d H:i:s").":".strval(json_encode($ret1)."\r\n"),FILE_APPEND);
    	//result
    	if(intval($ret['response_params']['success_amount']) > 0 || intval($ret1['response_params']['success_amount']) > 0){
    		echo 1;
    		exit;
    	}
		echo 0;
		exit;
    }
    
    private function pushIos($optional,$device_type,$message_type,$data,$limit,$push_type,$message_key){
    	$optional[Channel::DEVICE_TYPE]  = $device_type['ios'];
    	$optional[Channel::MESSAGE_TYPE] = $message_type['ios'];
    	$data['title'] = getstr($data['title'], 30);
		$data['content'] = getstr($data['content'], $limit, '...');
    	$message = array(
    			"aps" => array(
    					"alert" => array(
							'title'	=> $data['title'],
							'body'	=>	$data['content']
						),
    					"badge" => 1,
    			),
    			"extras" => $data['extras']
    	);
		file_put_contents("/tmp/pushData.txt",date("Y-m-d H:i:s").":".strval(json_encode($message)."\r\n"),FILE_APPEND);
    	$ret1 = $this->channel1->pushMessage ($push_type, $message, $message_key, $optional);
    	$res2 = $this->channel2->pushMessage ($push_type, $message, $message_key, $optional);
    	return $ret1;
    }
    
    private function pushAndroid($optional,$device_type,$message_type,$data,$limit,$push_type,$message_key){
    	$optional[Channel::DEVICE_TYPE]  = $device_type['android'];
    	$optional[Channel::MESSAGE_TYPE] = $message_type['android'];
    
    	$data['content']    =    getstr($data['content'], $limit, '...');
    	$message            =    var_json_encode($data);
    
    	$ret =  $this->channel->pushMessage ( $push_type, $message, $message_key, $optional );
    	return $ret;
    }
    
    private function deleteTag($req){
    	header("Content-type: application/json");
    	$channel 		= $this->version;
    	$tagName        = $req['tagName'];
    	$result   		= $this->$channel->deleteTag($tagName,$this->optional);
    	$result  = object_to_array($result);
    	if($result['request_id']){
    		return 1;
    	}
    	return 0;
    }
    
    private function queryBindList($req){
    	$data			= array();
    	$version_css	= array('channel'=>'','channel1'=>'','channel2'=>'');
    	$channel 		= $this->version;
    	$result   		= $this->$channel->queryUserTags($this->user_id,$this->optional);
    	$data     		= $result['response_params']['tags'];
    	
    	$version_css[$this->version] = 'selected';  
    	$res 	  = array('list'=>$data,'user_id'=>$this->user_id,'channel_id'=>$this->channel_id,'version'=>$this->version,'version_css'=>$version_css); 
    	return render('push',$res);
    }
  
   private function create_guid(){
  
    	$microTime = microtime();
    	
    	list($a_dec, $a_sec) = explode(" ", $microTime);
    	$dec_hex = dechex($a_dec* 1000000);
    	$sec_hex = dechex($a_sec);
    	$this->ensure_length($dec_hex, 5);
    	$this->ensure_length($sec_hex, 6);
    	$guid = "";
    	$guid .= $dec_hex;
    	$guid .= $this->create_guid_section(3);
    	$guid .= '-';
    	$guid .= $this->create_guid_section(4);
    	$guid .= '-';
    	$guid .= $this->create_guid_section(4);
    	$guid .= '-';
    	$guid .= $this->create_guid_section(4);
    	$guid .= '-';
    	$guid .= $sec_hex;
    	$guid .= $this->create_guid_section(6);
    	return $guid;
    }
    
    private function ensure_length(&$string, $length){
    	$strlen = strlen($string);
    	if($strlen < $length)
    	{
    		$string = str_pad($string,$length,"0");
    	}
    	else if($strlen > $length)
    	{
    		$string = substr($string, 0, $length);
    	}
    }
    
    private function create_guid_section($characters){
    
    	$return = "";
    	for($i=0; $i<$characters; $i++)
    	{
    	$return .= dechex(mt_rand(0,15));
    	}
    	return $return;
    }
    
    /**
     * 过滤传参
     * @param unknown $req
     * @return multitype:string unknown Ambigous <number, unknown> Ambigous <string, unknown> NULL number
     */
    private function filterArgumentsOfPassed($req) {
    	$title       =    "粉粉日记";
    	$content     =    "";
    	$link        =    "";
    	$action      =    "";
    	$tag_name    =    "";
    
    	if($req['push_title']) 		$title  	 = $req['push_title'];
    	if($req['push_content']) 	$content 	 = $req['push_content'];
    	if(empty($req['push_url'])){
    		return false;
    	}
    	//跳转
    	$acitonarr = $this->getPushAction($req['push_url'], $req['push_type']);
    	$link      = $acitonarr['link']; 	
    	$action    = $acitonarr['action'];  
    	if(empty($link) && empty($action)){
    		return false;
    	}
    	$data = array(
    			'title'		=>	$title,
    			'content'	=>	$content,
    			'extras'		=>	array(
    					'type'		=>	20,
    					'link'      =>  $link,
    					'action'	=>	$action,
    					'time'		=>	time()
    			)
    	);
    	return $data;
    }
    
    private function getPushAction($push_url,$push_type){
    	$res=array('action'=>'','link'=>'');
    	$parr = array();
    	$urlarr=parse_url($push_url);
    	parse_str($urlarr['query'],$parr);
    	switch ($push_type){
    		case 'push_action':
    			if ( $parr['op'] == 'getTopicCommentList' && $parr['tid'] > 0 && $parr['uid'] > 0 && $parr['gid'] > 0){
    				$res['action'] = "pinksns://group/topic?tid=".$parr['tid']."&uid=".$parr['uid']."&gid=".$parr['gid'];
    			}
    			break;
    		case 'push_diary_action':
    			if ($parr['ac'] == 'diary' && $parr['uid'] > 0 && $parr['diaryid'] > 0){
    				$res['action'] = "pinksns://diary/info?uid=".$parr['uid']."&bodyId=".$parr['diaryid'];
    			}
    			break;
    		case 'push_link':
    			if ($urlarr['scheme']=='http' || $urlarr['scheme']=='https'){
    				$res['link'] = $push_url;
    			}
    			break;
			case 'push_custom':
				$res['action'] = trim($push_url);
				break;
			case 'push_duiba':
				$res['action'] = trim($this->duibaBaseUrl.urlencode($push_url));
				break;
    	}
    	return $res;
    }
}

$req = request();
$push  = new Push($_SC ['apiurl']);

echo $push->execute($req['op']);
exit;
